<template>
  <BasicModal
    :canFullscreen="false"
    @cancel="handleCancel"
    v-bind="$attrs"
    @register="registerModal"
    title="其他设置"
    width="50%"
  >
    <div class="container">
      <div class="left">
        <div class="title mb-3">意见选择</div>
        <RadioGroup v-model:value="opinionChoose">
          <!-- <div class="check_item mb-2">
            <Radio value="缺省">缺省</Radio>
          </div> -->

          <div class="check_item mb-1" v-for="(item, index) in flowOutCheckList" :key="index">
            <Radio :value="item.choice">{{ item.choice }}</Radio>
          </div>
        </RadioGroup>
      </div>
      <div class="right">
        <BasicTable @selection-change="handleSelectItem" @register="registerOtherSettingsList">
          <template #emptyText>
            <div>暂无数据</div>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '编辑',

                    onClick: handleEdit.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable>
      </div>
    </div>
    <template #footer>
      <a-button @click="handleCancel">关闭</a-button>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </template>
    <FlowEditModal @register="registerFlowModal" @success="handleFlowSuccess" />
  </BasicModal>
</template>
<script lang="ts" setup name="OtherEditModal">
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { computed, ref, watch, nextTick } from 'vue';
  import { otherSettingsColumns } from './base_settings.data';
  import { cloneDeep } from 'lodash-es';
  import FlowEditModal from './FlowEditModal.vue';
  import { Radio } from 'ant-design-vue';
  const RadioGroup = Radio.Group;
  import modelerStore from '/@/store/modules/bpmnModeler';
  const modeler = modelerStore();

  const activities = computed(() => modeler.getActivities);
  const nodeItem = computed(() => modeler.nodeItem);
  const [registerModal, { closeModal }] = useModalInner(() => {
    getOutFlowNode(); // 找到流出的节点
    dealData(); //处理成前端显示数组里数组形式
    lastDealData(); //拿到后端数据用前端的覆盖掉

    findItem(opinionChoose.value);
  });

  const [
    registerOtherSettingsList,
    { getDataSource, setTableData, setSelectedRowKeys, clearSelectedRowKeys },
  ] = useTable({
    columns: otherSettingsColumns,
    pagination: false,
    rowSelection: {
      type: 'checkbox',
    },
    rowKey: `key`,
    scroll: { y: 550 },
    emptyDataIsShowTable: false,
    actionColumn: {
      width: 110,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });
  const flowOutCheckList = ref<any>([]);

  const flowArr = ref<any>([]);

  let isOutFlow = ref(false);
  let choice = ref('');
  function filterConditionId(arr, id) {
    for (var i = 0; i < arr.length; i++) {
      if (id === arr[i].sourceActivityId) {
        choice.value = arr[i].responseChoice || '缺省';
        isOutFlow.value = true;
        break;
      } else {
        isOutFlow.value = false;
        choice.value = '';
        if (arr[i].children && arr[i].children.length > 0 && !isOutFlow.value) {
          isOutFlow.value = false;
          choice.value = '';
          filterConditionId(arr[i].children, id);
        }
      }
    }

    return { isOutFlow: isOutFlow.value, choice: choice.value };
  }
  function getOutFlowNode() {
    const flowList = cloneDeep(activities.value);
    const flowArrTask: any = flowList.filter((i) => i.activityType !== 5);
    const flowArrRefuse: any = [];
    flowList.forEach(async (item) => {
      if (item.condition) {
        isOutFlow.value = false;
        choice.value = '';
        const res = filterConditionId(item.condition?.children, nodeItem.value?.activityId);

        if (
          res.isOutFlow &&
          (item.activityType === 1 || item.activityType === 0 || item.activityType === 2)
        ) {
          item.choice = res.choice;
          flowArr.value.push(item);
        } else if (res.isOutFlow && item.activityType === 5) {
          flowArrRefuse.push(item);
        }
      }
    });
    flowArrRefuse.forEach((item) => {
      flowArrTask.forEach((task) => {
        if (task.condition) {
          isOutFlow.value = false;
          choice.value = '';
          const res = filterConditionId(task.condition?.children, item.activityId);
          if (res.isOutFlow) {
            isOutFlow.value = false;
            choice.value = '';
            const resRefuse = filterConditionId(
              item.condition?.children,
              nodeItem.value?.activityId,
            );
            if (resRefuse.isOutFlow) {
              task.choice = resRefuse.choice;
            }
            flowArr.value.push(task);
          }
        }
      });
    });
  }

  function dealData() {
    // 先获取步骤里的角色
    const roleList: any = [];
    flowArr.value.forEach((item) => {
      item.R0.forEach((value) => {
        if (!roleList.includes(value.value) && (value.option?.roleType > 0 || value.value > 0)) {
          roleList.push({ ...value, choice: item.choice });
        }
      });
    });

    console.log(roleList, 123);
    // 过滤步骤的限制范围>0
    flowArr.value = flowArr.value.filter((i) => i.rangeType > 0);
    const activityArr = flowArr.value.map((i) => ({
      activityID: i.activityId,
      choice: i.choice,
      name: i.activityName,
      showName: '',
      operationPermissions: 1,
      roleID: '',
      type: 1,
      key: `${i.choice}1${i.activityId}`,
    }));
    // 添加角色
    const roleArr = roleList
      .map((i) => ({
        activityID: '',
        choice: i.choice,
        name: i.label,
        showName: '',
        operationPermissions: 1,
        roleID: i.value,
        type: 2,
        key: `2${i.value}`,
      }))
      .filter((v) => v.roleID !== 1);
    const arr: any = nodeItem.value?.baseInfo?.responseChoices?.split(';')?.filter((i) => i) || [];
    // 添加同意拒绝数据
    flowOutCheckList.value = arr.map((i, index) => {
      const itemArr = activityArr.filter((v) => v.choice === i);
      const itemRoleArr = roleArr.filter((v) => v.choice === i);
      return {
        limitedCount: 0,
        nextTransType: '',
        choice: i,
        key: index + 1,
        transRoles: [
          ...cloneDeep(itemRoleArr.map((r) => ({ ...r, key: `${i}2${i.roleID}` }))),
          ...itemArr,
        ],
      };
    });
    //  添加缺省数据
    flowOutCheckList.value.unshift({
      limitedCount: 0,
      nextTransType: '',
      choice: '缺省',
      key: 0,
      transRoles: [
        ...cloneDeep(roleArr.map((r, index) => ({ ...r, key: `缺省${index}` }))),
        ...cloneDeep(activityArr.map((r) => ({ ...r, key: `缺省${r.activityID}` }))),
      ],
    });
    console.log(flowOutCheckList);
  }
  function lastDealData() {
    const transChoicesList = computed(() => modeler.nodeItem?.transChoices);
    if (!transChoicesList.value.length) {
      return;
    }
    flowOutCheckList.value.forEach((flow) => {
      transChoicesList.value.forEach((trans) => {
        if (flow.key == trans.choice) {
          flow.transRoles.forEach((flowItem) => {
            trans.transRoles.forEach((transItem) => {
              if (
                (transItem.type == 1 && flowItem.activityID == transItem.activityID) ||
                (transItem.type == 2 && flowItem.roleID == transItem.roleID)
              ) {
                flowItem.showName = transItem.showName;
                flowItem.isCheck = true;
                flowItem.operationPermissions = transItem.operationPermissions;
              }
            });
          });
        }
      });
    });
  }

  const opinionChoose = ref('缺省');
  const transRolesIndex = ref(0);
  function findItem(choice) {
    nextTick(() => {
      clearSelectedRowKeys();
      const index = flowOutCheckList.value.findIndex((i) => i.choice === choice);
      transRolesIndex.value = index;
      const selectKeys = flowOutCheckList.value[index]?.transRoles
        .map((i) => (i.isCheck ? i.key : ''))
        .filter((v) => v);
      setTableData(flowOutCheckList.value[index]?.transRoles);
      setSelectedRowKeys(selectKeys);
    });
  }
  watch(
    () => opinionChoose.value,
    (val: any) => {
      findItem(val);
    },
  );

  const [registerFlowModal, { openModal: openFlowModal }] = useModal();

  function handleEdit(record: Recordable, $event) {
    $event.stopPropagation();
    openFlowModal(true, {
      ...record,
    });
  }
  function handleFlowSuccess(value) {
    // console.log(id);
    // const item: any = transRoles.value.find((i: any) => i.activityID === id || i.roleID === id);
    // console.log(item);
    // if (item) {
    //   item.showName = value.showName;
    //   item.operationPermissions = value.operationPermissions;
    // }
    flowOutCheckList.value[transRolesIndex.value].transRoles.forEach((item) => {
      if (
        (value.type === 1 && item.activityID === value.id) ||
        (value.type === 2 && item.roleID === value.id)
      ) {
        item.showName = value.showName;
        item.operationPermissions = value.operationPermissions;
        setTableData(flowOutCheckList.value[transRolesIndex.value]?.transRoles);
      }
    });
  }
  function handleCancel() {
    flowOutCheckList.value = [];
    flowArr.value = [];
    setTableData([]);
    closeModal();
  }
  function handleSelectItem({ keys }) {
    const tableList = getDataSource();
    tableList.forEach((item) => {
      if (keys.includes(item.key)) {
        item.isCheck = true;
      } else {
        item.isCheck = false;
      }
    });
    // rows.forEach((item) => {
    //   item.isCheck = true;
    // });
  }
  function handleSubmit() {
    const arr: any = [];
    flowOutCheckList.value.forEach((item) => {
      item.choice = item.key;
      item.transRoles = item.transRoles.filter((i) => i.isCheck);
      if (item.transRoles.length > 0) {
        arr.push(item);
      }
    });
    modeler.setActivitiesItem(modeler.getActiveId, 'transChoices', arr);
    handleCancel();
  }
</script>
<style lang="less" scoped>
  .container {
    display: flex;
    height: 580px;
    overflow-y: auto;

    .left {
      width: 15%;
      padding: 16px 0 0 16px;

      .title {
        font-weight: 600;
        font-size: 16px;
      }
    }

    .right {
      width: 85%;
    }
  }

  :deep(.ant-table-tbody) {
    > tr.ant-table-row-selected > td {
      background-color: #f8f8f8;
    }
  }
</style>
